package postgresql

import (
	"context"
	"github.com/jackc/pgx/v4/pgxpool"
)

type Store struct {
	db *pgxpool.Pool
}

type Comment struct {
	Id       int
	Content  string
	NewsId   int
	ParentId int
}

// New create a new store
func New(constr string) (*Store, error) {
	db, err := pgxpool.Connect(context.Background(), constr)

	if err != nil {
		return nil, err
	}

	return &Store{db}, nil
}

// CommentsByNewsId return comments for a newsId
func (s *Store) CommentsByNewsId(newsId int) ([]Comment, error) {
	rows, err := s.db.Query(context.Background(),
		`SELECT id,
				content,
				news_id,
				parent_id
		FROM comments
		WHERE news_id = $1`,
		newsId)
	if err != nil {
		return nil, err
	}
	var comments []Comment
	for rows.Next() {
		var comment Comment
		err = rows.Scan(&comment.Id,
			&comment.Content,
			&comment.NewsId,
			&comment.ParentId)
		if err != nil {
			return nil, err
		}
		comments = append(comments, comment)
	}
	return comments, nil
}

// AddComment add a comment
func (s *Store) AddComment(c Comment) error {
	_, err := s.db.Exec(context.Background(),
		`INSERT INTO comments (content, news_id, parent_id) VALUES ($1, $2, $3)`,
		c.Content, c.NewsId, c.ParentId)
	return err
}
